package com.yzycoc.coc.gf.util;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import lombok.extern.slf4j.Slf4j;

/**
 * 文件配置
 * 创建时间： 2024/6/7
 *
 * @author yzy
 * @version 1.0
 **/
@Slf4j
public class ConfigFileUtil {

    private String fileName;

    private String groupName;

    public ConfigFileUtil(String fileName) {
        this.fileName = System.getProperty("user.dir") + "/data/" + fileName;
        this.groupName = "default";
    }

    public ConfigFileUtil(String fileName, String groupName) {
        this.fileName = fileName;
        this.groupName = groupName;
    }

    public Setting getSetting() {
        return new Setting(FileUtil.touch(fileName), CharsetUtil.CHARSET_UTF_8, true);
    }

    // 读取配置的方法
    public String getConfig(String key) {
        try {
            return this.getSetting().getByGroup(key, groupName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Integer getInteger(String key) {
        String str = getConfig(key);
        if (StrUtil.isNotEmpty(str)) {
            try {
                return Integer.valueOf(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public Long getLong(String key) {
        String str = getConfig(key);
        if (StrUtil.isNotEmpty(str)) {
            try {
                return Long.valueOf(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public Boolean getBoolean(String key) {
        String str = getConfig(key);
        if (StrUtil.isNotEmpty(str)) {
            try {
                return Boolean.valueOf(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public void put(String key, Object value) {
        setConfig(key, value);
    }

    // 写入配置的方法
    public void setConfig(String key, Object value) {
        Setting setting = this.getSetting();
        setting.setByGroup(key, groupName, String.valueOf(value));
        setting.store();
    }


}
